package cn.xy.base.server.configure;

import cn.hutool.core.text.CharSequenceUtil;
import cn.xy.base.server.utils.AesService;
import com.rustic.server.SpringContext;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * aes加密工具类
 *
 *  @author xy
 */
public class AesTypeHandler extends BaseTypeHandler<String> {

    private AesService aesService;

    public AesService getAesService() {
        if (this.aesService != null) {
            return this.aesService;
        }
        this.aesService = SpringContext.getBean(AesService.class);
        return this.aesService;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, getAesService().encrypt(parameter));
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String columnValue = resultSet.getString(columnName);
        return CharSequenceUtil.isEmpty(columnValue) ? columnValue : getAesService().decrypt(columnValue);
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String columnValue = resultSet.getString(columnIndex);
        return CharSequenceUtil.isEmpty(columnValue) ? columnValue : getAesService().decrypt(columnValue);
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String columnValue = callableStatement.getString(columnIndex);
        return CharSequenceUtil.isEmpty(columnValue) ? columnValue : getAesService().decrypt(columnValue);
    }
}
